﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using Microsoft.EntityFrameworkCore;
using AJWPFAdmin.Core.Models.EF.Tables;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AJWPFAdmin.Modules.Common.Views;
using AJWPFAdmin.Services;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Validation;
using Yitter.IdGenerator;
using AJWPFAdmin.Core.Excel;
using AJWPFAdmin.Services.Models;
using DocumentFormat.OpenXml.Office.LongProperties;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Core.Components.ViewModels;
using AJWPFAdmin.Core.Components.Views;

namespace EntranceGuardManager.Modules.Main.ViewModels
{

    public class CarListViewModel : BindableBase, INavigationAware
    {
        private bool _syncFlag;

        private readonly static List<AJTableColumnItem> _taiZhangColumns = new List<AJTableColumnItem> {
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.PlateColor),
                        Title = "号牌颜色",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.TruckTypeName),
                        Title = "车辆类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.RegDate),
                        Title = "注册登记日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.VIN),
                        Title = "车辆识别代码(VIN)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarBrandModel),
                        Title = "车辆品牌型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.FuelTypeName),
                        Title = "燃料类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EmissionStandard),
                        Title = "排放标准",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.NetworkingStatus),
                        Title = "联网状态",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已联网" : "未联网";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.UsageDescription),
                        Title = "使用性质",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsName),
                        Title = "进厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsType),
                        Title = "进厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsVolume),
                        Title = "进厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsName),
                        Title = "出厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsType),
                        Title = "出厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsVolume),
                        Title = "出厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Attachments),
                        Title = "随车清单",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "AttachmentsImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EmissionStandardImages),
                        Title = "排放阶段图片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "EmissionStandardImagesImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.VehicleLicense),
                        Title = "行驶证",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "VehicleLicenseImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarImage),
                        Title = "车辆图片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "CarImageImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Nameplate),
                        Title = "整车(机)铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "NameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MachineEnvProtectionLabel),
                        Title = "机械环保信息标签",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "MachineEnvProtectionLabelImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Synchronized),
                        Title = "是否同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.SyncResult),
                        Title = "同步结果",
                    },
                    new AJTableColumnItem
                    {
                        Title = "操作",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "TableOperatioin"
                        },
                        Fixed = AJTableColumnFixedType.Right,
                        Width = new DataGridLength(160),
                    }
            };

        private readonly static List<AJTableColumnItem> _factoryColumns = new List<AJTableColumnItem> {
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EnvRegCode),
                        Title = "环保登记编码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.VIN),
                        Title = "车辆识别代码(VIN)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.ProductionDate),
                        Title = "生产日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.RegDate),
                        Title = "注册登记日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarBrandModel),
                        Title = "车辆品牌型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.FuelTypeName),
                        Title = "燃料类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EmissionStandard),
                        Title = "排放标准",
                    },
                     new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.NetworkingStatus),
                        Title = "联网状态",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已联网" : "未联网";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsName),
                        Title = "进厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsType),
                        Title = "进厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsVolume),
                        Title = "进厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsName),
                        Title = "出厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsType),
                        Title = "出厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsVolume),
                        Title = "出厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Attachments),
                        Title = "随车清单",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "AttachmentsImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EmissionStandardImages),
                        Title = "排放阶段图片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "EmissionStandardImagesImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.VehicleLicense),
                        Title = "行驶证",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "VehicleLicenseImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarImage),
                        Title = "车辆图片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "CarImageImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Nameplate),
                        Title = "整车(机)铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "NameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MachineEnvProtectionLabel),
                        Title = "机械环保信息标签",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "MachineEnvProtectionLabelImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Owner),
                        Title = "车辆所有人(单位)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Synchronized),
                        Title = "是否同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.SyncResult),
                        Title = "同步结果",
                    },
                    new AJTableColumnItem
                    {
                        Title = "操作",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "TableOperatioin"
                        },
                        Fixed = AJTableColumnFixedType.Right,
                        Width = new DataGridLength(160),
                    }
            };

        private readonly static List<AJTableColumnItem> _machineColumns = new List<AJTableColumnItem> {
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EnvRegCode),
                        Title = "环保登记编码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MechanicalProdDate),
                        Title = "机械生产日期",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EmissionStandard),
                        Title = "排放标准",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.FuelTypeName),
                        Title = "燃料类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MachineType),
                        Title = "机械种类",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.PIN),
                        Title = "机械环保代码PIN",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MachineModel),
                        Title = "机械型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EngineModel),
                        Title = "发动机型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EngineManufacturer),
                        Title = "发动机生产厂",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EngineNo),
                        Title = "发动机编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Nameplate),
                        Title = "整车(机)铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "NameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.EngineNameplate),
                        Title = "发动机铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "EngineNameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.MachineEnvProtectionLabel),
                        Title = "机械环保信息标签",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "MachineEnvProtectionLabelImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Owner),
                        Title = "所属人(单位)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsName),
                        Title = "进厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsType),
                        Title = "进厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsVolume),
                        Title = "进厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsName),
                        Title = "出厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsType),
                        Title = "出厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsVolume),
                        Title = "出厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.Synchronized),
                        Title = "是否同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.SyncResult),
                        Title = "同步结果",
                    },
                    new AJTableColumnItem
                    {
                        Title = "操作",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "TableOperatioin"
                        },
                        Fixed = AJTableColumnFixedType.Right,
                        Width = new DataGridLength(160),
                    }
            };

        private readonly static List<AJTableColumnItem> _tempCarColumns = new List<AJTableColumnItem> {

                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.PlateColor),
                        Title = "车牌颜色",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsName),
                        Title = "进厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsType),
                        Title = "进厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.InGoodsVolume),
                        Title = "进厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsName),
                        Title = "出厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsType),
                        Title = "出厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(Car.OutGoodsVolume),
                        Title = "出厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        Title = "操作",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "TableOperatioin"
                        },
                        Fixed = AJTableColumnFixedType.Right,
                        Width = new DataGridLength(160),
                    }
            };

        private List<AJTableColumnItem> _defaultColumns;

        private ShippingRecordExportConfig _exportConfig;
        public ShippingRecordExportConfig ExportConfig
        {
            get { return _exportConfig; }
            set { SetProperty(ref _exportConfig, value); }
        }

        private AJTableImportOptions _importOptions;
        public AJTableImportOptions ImportOptions
        {
            get { return _importOptions; }
            set { SetProperty(ref _importOptions, value); }
        }

        private AJTableRowSelection _rowSelection;
        public AJTableRowSelection RowSelection
        {
            get => _rowSelection;
            set => SetProperty(ref _rowSelection, value);
        }

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }

        private AJTableSearchFormConfig _formConfig;

        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private DelegateCommand<Car> _openCarImagePreviewCmd;
        public DelegateCommand<Car> OpenCarImagePreviewCmd =>
            _openCarImagePreviewCmd ?? (_openCarImagePreviewCmd = new DelegateCommand<Car>(ExecuteOpenCarImagePreviewCmd));

        void ExecuteOpenCarImagePreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.CarImage);
        }

        private DelegateCommand<Car> _openEmissionStandardImagesPreviewCmd;
        public DelegateCommand<Car> OpenEmissionStandardImagesPreviewCmd =>
            _openEmissionStandardImagesPreviewCmd ?? (_openEmissionStandardImagesPreviewCmd = new DelegateCommand<Car>(ExecuteOpenEmissionStandardImagesPreviewCmd));

        void ExecuteOpenEmissionStandardImagesPreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.EmissionStandardImages);
        }

        private DelegateCommand<Car> _openAttachmentsPreviewCmd;
        public DelegateCommand<Car> OpenAttachmentsPreviewCmd =>
            _openAttachmentsPreviewCmd ?? (_openAttachmentsPreviewCmd = new DelegateCommand<Car>(ExecuteOpenAttachmentsPreviewCmd));

        void ExecuteOpenAttachmentsPreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.Attachments);
        }

        private DelegateCommand<Car> _openVehicleLicensePreviewCmd;
        public DelegateCommand<Car> OpenVehicleLicensePreviewCmd =>
            _openVehicleLicensePreviewCmd ?? (_openVehicleLicensePreviewCmd = new DelegateCommand<Car>(ExecuteOpenVehicleLicensePreviewCmd));

        void ExecuteOpenVehicleLicensePreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.VehicleLicense);
        }

        private DelegateCommand<Car> _openNameplatePreviewCmd;
        public DelegateCommand<Car> OpenNameplatePreviewCmd =>
            _openNameplatePreviewCmd ?? (_openNameplatePreviewCmd = new DelegateCommand<Car>(ExecuteOpenNameplatePreviewCmd));

        void ExecuteOpenNameplatePreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.Nameplate);
        }

        private DelegateCommand<Car> _openEngineNameplatePreviewCmd;
        public DelegateCommand<Car> OpenEngineNameplatePreviewCmd =>
            _openEngineNameplatePreviewCmd ?? (_openEngineNameplatePreviewCmd = new DelegateCommand<Car>(ExecuteOpenEngineNameplatePreviewCmd));

        void ExecuteOpenEngineNameplatePreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.EngineNameplate);
        }

        private DelegateCommand<Car> _openMachineEnvProtectionLabelPreviewCmd;
        public DelegateCommand<Car> OpenMachineEnvProtectionLabelPreviewCmd =>
            _openMachineEnvProtectionLabelPreviewCmd ?? (_openMachineEnvProtectionLabelPreviewCmd = new DelegateCommand<Car>(ExecuteOpenMachineEnvProtectionLabelPreviewCmd));

        void ExecuteOpenMachineEnvProtectionLabelPreviewCmd(Car parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.MachineEnvProtectionLabel);
        }

        void ExecuteOpenImagePreviewCmd(string carNo, string parameter)
        {
            var array = CommonUtil.TryGetJSONObject<string[]>(parameter) ?? Array.Empty<string>();
            if (array.Length > 0)
            {
                array = array.Select(p => _carIdentificationConfig.CompleteFileUrl(carNo, p)).ToArray();
            }

            var @params = new DialogParameters
            {
                { "data", CommonUtil.AJSerializeObject(array) },
            };
            _dialogSvc.ShowDialog(nameof(ImageShowCaseDialog), @params, r =>
            {

            });
        }

        private DelegateCommand<Car> _editCmd;
        public DelegateCommand<Car> EditCmd =>
            _editCmd ?? (_editCmd = new DelegateCommand<Car>(ExecuteEditCmd));

        void ExecuteEditCmd(Car parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                { "typeOptions", _typeOptions },
            };
            _dialogSvc.ShowDialog(nameof(CarForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    FetchOptions.RequestRefresh(false);
                }
            });
        }


        private DelegateCommand<Car> _deleteCmd;
        public DelegateCommand<Car> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<Car>(ExecuteDeleteCmd));

        async void ExecuteDeleteCmd(Car parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "删除确认",
                Message = parameter.Synchronized ? $"该数据已和线上接口同步,是否继续删除?" : $"即将删除 {parameter.CarNo} ?"
            });

            if (confirm)
            {
                db.Cars.Remove(parameter);
                await db.SaveChangesAsync();

                FetchOptions.RequestRefresh(false);
            }
        }

        private DelegateCommand<string> _toggleExportConfigCmd;
        public DelegateCommand<string> ToggleExportConfigCmd =>
            _toggleExportConfigCmd ?? (_toggleExportConfigCmd = new DelegateCommand<string>(ExecutetoggleExportConfigCmd));

        void ExecutetoggleExportConfigCmd(string parameter)
        {
            ExportConfig.Open = parameter.Equals("true", StringComparison.OrdinalIgnoreCase);
        }

        private DelegateCommand _exportCmd;
        public DelegateCommand ExportCmd =>
            _exportCmd ?? (_exportCmd = new DelegateCommand(ExecuteExportCmd));

        void ExecuteExportCmd()
        {
            FetchOptions.RequestExport();
        }

        private DelegateCommand _deleteSelectedCmd;
        public DelegateCommand DeleteSelectedCmd =>
            _deleteSelectedCmd ?? (_deleteSelectedCmd = new DelegateCommand(ExecuteDeleteSelectedCmd, CanExecuteDeleteSelectedCmd));

        void ExecuteDeleteSelectedCmd()
        {
            var ids = SelectedRows.Select(p => p.Id).ToArray();

            AJCommonDialog.ShowDialog(new AJCommonDialogViewModel.AJCommonDialogParams
            {
                Title = $"确定删除 {ids.Length} 条数据",
                Message = "删除后数据不可恢复,是否确定继续",
                Type = CommonDialogType.Warning,
                ShowCancel = true
            }, async (ret) =>
            {
                if (ret.Result == ButtonResult.OK)
                {
                    await db.Cars.Where(p => ids.Contains(p.Id)).ExecuteDeleteAsync();

                    FetchOptions.RequestRefresh(false);
                }
            });

        }

        bool CanExecuteDeleteSelectedCmd()
        {
            return SelectedRows?.Count > 0;
        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _typeOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> TypeOptions
        {
            get { return _typeOptions; }
            set
            {
                SetProperty(ref _typeOptions, value);
            }
        }

        private List<Car> _selectedRows;
        public List<Car> SelectedRows
        {
            get => _selectedRows;
            set => SetProperty(ref _selectedRows, value);
        }

        private long[] _ledgerCarTypes;

        private IDialogService _dialogSvc;
        private DbService db;
        private SystemUserService _sysUserSvc;
        private CarIdentificationConfig _carIdentificationConfig;
        private AppointAPISvc _appointSvc;

        public CarListViewModel(DbService dbIns,
            AppointAPISvc appointAPISvc,
            SystemUserService sysUserSvc,
            IEventAggregator eventAggregator, IDialogService dialogSvc)
        {
            _appointSvc = appointAPISvc;
            _sysUserSvc = sysUserSvc;
            _dialogSvc = dialogSvc;
            RowSelection = new AJTableRowSelection
            {
                Width = new DataGridLength(10),
                OnChangeHandler = (items) =>
                {
                    var list = new List<Car>();
                    foreach (var item in items)
                    {
                        if (item is Car rowItem)
                        {
                            list.Add(rowItem);
                        }
                    }
                    SelectedRows = list;
                    DeleteSelectedCmd?.RaiseCanExecuteChanged();
                }
            };
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() => Loading = false);
            ExportConfig = new ShippingRecordExportConfig();

            var plateColorStrs = string.Join("/", CommonUtil.EnumToDictionary<CarPlateColor>(null).Select(p => p.Key));

            var eStandardStrs = string.Join("/", CommonUtil.EnumToDictionary<EmissionStandard>(null).Select(p => p.Key));
            var vehicleTypeStrs = string.Join("/", CommonUtil.EnumToDictionary<VehicleType>(null).Select(p => p.Key));

            ImportOptions = new AJTableImportOptions
            {
                ImportType = typeof(CarImportModel),
                TemplateRowsHandler = () =>
                {
                    return new List<object> {
                        new CarImportModel
                        {
                            CarNo = "贵CH5205",
                            PlateColor = plateColorStrs,
                            ExpireDate = "选填,如:2024-11-16 11:58:00",
                            TypeName = "免检车/固定车",
                        }
                    };
                },
                ImportDataItemProcessHandler = (item) =>
                {
                    var result = new ProcessResult();

                    if (item is not CarImportModel model)
                    {
                        result.SetError($"实体数据转换失败");
                        return result;
                    }
                    var checkRet = FormChecker.RequireAndLength(model.CarNo, 120, "车号");
                    if (!checkRet.Success)
                    {
                        result.SetError(checkRet.Message);
                        return result;
                    }
                    checkRet = FormChecker.IsEnum(model.TypeName, typeof(CarTypeEnum), "车辆类型");
                    if (!checkRet.Success)
                    {
                        result.SetError(checkRet.Message);
                        return result;
                    }

                    checkRet = FormChecker.IsEnum(model.PlateColor, typeof(CarPlateColor), "车牌颜色");
                    if (!checkRet.Success)
                    {
                        result.SetError(checkRet.Message);
                        return result;
                    }

                    var carNo = model.CarNo;

                    if (db.Cars.Any(p => p.CarNo == carNo))
                    {
                        result.SetError($"{carNo} 已存在");
                        return result;
                    }
                    var type = Enum.Parse<CarTypeEnum>(model.TypeName, true);
                    var record = new Car
                    {
                        Id = YitIdHelper.NextId(),
                        CarNo = carNo,
                        PlateColor = Enum.Parse<CarPlateColor>(model.PlateColor, true),
                        TypeId = (long)type,
                        TypeName = model.TypeName,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    };

                    db.Cars.Add(record);

                    result.SetSuccess();

                    return result;
                },
                ImportCompleteHandler = async () =>
                {
                    var result = new ProcessResult();
                    result.SetSuccess();
                    await db.SaveChangesAsync();
                    return result;
                }
            };

            _ledgerCarTypes = new long[]
            {
                (long)CarTypeEnum.进出厂车,
                (long)CarTypeEnum.固定车,
                (long)CarTypeEnum.非道路移动机械,
            };
            var isDefaultAPI = _appointSvc.API is DefaultAppointAPI;
            FetchOptions = new AJTableFetchOptions
            {
                ExportFileName = "车辆记录导出",
                Handle = async (formCfg, pageCfg) =>
                {

                    var name = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(Car.CarNo)).Value?.ToString();

                    var syncFormSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(Car.Synchronized));

                    var typeformSchema = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(Car.TypeId));

                    var typeId = typeformSchema.Value == null ? new long?() : (long)typeformSchema.Value;

                    if (!_syncFlag)
                    {
                        typeId = null;
                    }

                    if (typeId.HasValue)
                    {
                        var typeEnum = (CarTypeEnum)((int)typeId.GetValueOrDefault());
                        switch (typeEnum)
                        {
                            case CarTypeEnum.固定车:
                            case CarTypeEnum.进出厂车:
                                Columns = _taiZhangColumns.Select(p => p).ToList();
                                break;
                            case CarTypeEnum.厂内运输车:
                                Columns = _factoryColumns.Select(p => p).ToList();
                                break;
                            case CarTypeEnum.非道路移动机械:
                                Columns = _machineColumns.Select(p => p).ToList();
                                break;
                            case CarTypeEnum.临时车:
                            case CarTypeEnum.免检车:
                                Columns = _tempCarColumns.Select(p => p).ToList();
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        Columns = _defaultColumns.Select(p => p).ToList();
                    }

                    var dates = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(Car.CreateDate)).Value as ObservableCollection<DateTime?>;

                    var list = await db.Cars
                        .LikeOrLike(name, p => p.CarNo)
                        .IfWhere(() => typeId.HasValue, p => p.TypeId == typeId)
                        .IfWhere(() => !_syncFlag, p => _ledgerCarTypes.Contains(p.TypeId))
                        .BetweenInDates(dates.ToArray(), p => p.CreateDate)
                        .OrderByDescending(p => p.CreateDate)
                        .IfWhere(() => !isDefaultAPI, p => p.Synchronized == _syncFlag)
                        .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    if ((TypeOptions?.Count).GetValueOrDefault() == 0)
                    {
                        var options = await db.CarTypes.AsNoTracking()
                        .OrderBy(p => p.Id)
                        .Select(p => new AJTableFormSchemaItemOptions
                        {
                            Value = p.Id,
                            Label = p.Name
                        }).ToListAsync();

                        TypeOptions = typeformSchema.Options
                            = new ObservableCollection<AJTableFormSchemaItemOptions>(options);
                    }

                    if (formCfg.IsExport)
                    {
                        // 如果是导出要补全图片文件路径
                        list.Data.ForEach(r =>
                        {
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.Attachments));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.CarImage));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.VehicleLicense));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.Nameplate));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.EngineNameplate));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.MachineEnvProtectionLabel));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.EmissionStandardImages));

                        });
                    }

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "搜索车牌号",
                        Field = nameof(Car.CarNo),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "类型",
                        Field = nameof(Car.TypeId),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Labels = new string[]{ "创建开始日期","创建结束日期" },
                        Field = nameof(Car.CreateDate),
                        Type = AJTableSchemaType.RangePicker,
                        Value = new ObservableCollection<DateTime?>( new DateTime?[2]{null,null}),
                        IsPopular = true,
                    },
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            //_sysUserSvc.CachedColumnsConfig.TryGetValue(nameof(CarListViewModel).ToLower(), out var columnNames);
            //columnNames ??= new string[0];
            _defaultColumns = new List<AJTableColumnItem>();

            var props = typeof(Car).GetRuntimeProperties();

            foreach (var prop in props)
            {
                var notmappedAttr = prop.GetCustomAttribute<NotMappedAttribute>();

                if (notmappedAttr != null
                    || prop.Name == nameof(Car.Id)
                    || prop.Name == nameof(Car.PId)
                    || prop.Name == nameof(Car.TypeId)
                    || prop.Name == nameof(Car.TruckTypeCode)
                    || prop.Name == nameof(Car.FuelTypeCode))
                {
                    continue;
                }

                var displayAttr = prop.GetCustomAttribute<DisplayAttribute>();

                var column = new AJTableColumnItem
                {
                    DataIndex = prop.Name,
                    Title = displayAttr?.Name ?? prop.Name,
                };

                if (prop.Name == nameof(Car.NetworkingStatus))
                {
                    column.Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return (bool)val ? "已联网" : "未联网";
                        }
                    };
                }

                if (prop.Name == nameof(Car.Synchronized))
                {
                    column.Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return (bool)val ? "已同步" : "未同步";
                        }
                    };
                }

                if (prop.Name == nameof(Car.Attachments)
                    || prop.Name == nameof(Car.CarImage)
                    || prop.Name == nameof(Car.VehicleLicense)
                    || prop.Name == nameof(Car.Nameplate)
                    || prop.Name == nameof(Car.EngineNameplate)
                    || prop.Name == nameof(Car.MachineEnvProtectionLabel)
                    || prop.Name == nameof(Car.EmissionStandardImages))
                {
                    column.CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = $"{prop.Name}ImagePreview",
                        IsImage = true
                    };
                }

                if (prop.PropertyType == typeof(DateTime?))
                {
                    column.Formatter = prop.Name == nameof(Car.ExpireDate)
                        ? new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null
                                ? "永久有效"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                        : new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null
                                ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        };

                }
                if (prop.PropertyType == typeof(DateTime))
                {
                    column.Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    };
                }

                if (prop.PropertyType == typeof(decimal))
                {
                    column.Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return ((decimal)val).ToString("N2");
                        }
                    };
                }
                //column.Visible = columnNames.Length > 0 ? columnNames.Any(p => p == column.Title) : true;
                column.Visible = true;
                _defaultColumns.Add(column);
            }
            _defaultColumns.Add(new AJTableColumnItem
            {
                Title = "操作",
                CustomTemplate = new AJTableCustomTemplate
                {
                    Key = "TableOperatioin"
                },
                Fixed = AJTableColumnFixedType.Right,
                Width = new DataGridLength(160),
            });
            //Columns = _defaultColumns.Select(p => p).ToList();

            db = dbIns;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue("params", out _syncFlag);
            //ExecuteGetListCmd();
            _carIdentificationConfig = CarIdentificationConfigExt.GetCarIdentificationConfig(db);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            //_sysUserSvc.SaveColumnsConfig(nameof(CarListViewModel).ToLower(),
            //    Columns.Where(p => p.Visible).Select(p => p.Title).ToArray());
        }

        public class CarImportModel
        {
            [AJExportField(ColumnName = "车牌号", ColumnIndex = 1)]
            [AJImportField(ColumnName = "车牌号", ColumnIndex = 1)]
            public string CarNo { get; set; }

            [AJExportField(ColumnName = "车牌颜色", ColumnIndex = 2)]
            [AJImportField(ColumnName = "车牌颜色", ColumnIndex = 2)]
            public new string PlateColor { get; set; }

            [AJExportField(ColumnName = "到期时间", ColumnIndex = 3)]
            [AJImportField(ColumnName = "到期时间", ColumnIndex = 3)]
            public new string ExpireDate { get; set; }

            [AJExportField(ColumnName = "车系统类型", ColumnIndex = 4)]
            [AJImportField(ColumnName = "车系统类型", ColumnIndex = 4)]
            public string TypeName { get; set; }

        }
    }
}
